package com.sky.config;

import com.google.gson.Gson;
import okhttp3.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

//使用DeepSeek中问题解决方案
/*
1.打开服务：
bash:"ollama serve"

2.确认Ollama服务状态
使用以下命令检查Ollama服务是否在运行：
bash: "netstat -ano | findstr :11434"

3.检查模型加载状态
确认模型deepseek-r1:7b已正确加载：
bash:"ollama list"
如果模型未加载，重新加载模型：
bash: "ollama pull deepseek-r1:7b"

4.关闭防火墙
*/
//使用方法可见：src/test/java/com/youy/Test1.java
public class DeepSeek_stream {
    static class DeepSeekResponse {
        private String model;
        private String created_at;
        private String response;

        // Getters
        public String getResponse() {
            return response;
        }
    }
    static class RequestBodyData {
        String model = "deepseek-r1:7b"; // 确认模型名称
        String prompt;//问题内容
        boolean stream = true; // 开启流式输出
    }
    private static final String API_URL = "http://localhost:11434/api/generate";
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    private static final Gson gson = new Gson();

    // 定义回调接口
    public interface ResponseCallback {
        void onDataReceived(String chunk);
    }

    public void answer(String problem, ResponseCallback callback) throws IOException{
        //调整OkHttp的超时设置至60秒：
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)  // 连接超时
                .readTimeout(60, TimeUnit.SECONDS)     // 读取超时
                .build();
        RequestBodyData requestBody = new RequestBodyData();
        requestBody.prompt = problem;
        String json = gson.toJson(requestBody);

        Request request = new Request.Builder()
                .url(API_URL)
                .post(RequestBody.create(json, JSON))
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code: " + response);
            }

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(response.body().byteStream())
            );

            String line;
            while ((line = reader.readLine()) != null) {
                DeepSeekResponse ollamaResponse = gson.fromJson(line, DeepSeekResponse.class);
                String oneByte = ollamaResponse.getResponse();
                callback.onDataReceived(oneByte); // 实时回调数据
            }
        }
    }

}
